package com.project.controller;

import com.alibaba.fastjson.JSON;
import com.project.bean.SupplierBean;
import com.project.dto.SupplierDto;
import com.project.service.ISupplierService;
import com.project.util.CreateToken;
import com.project.util.SupplierThreadLocal;
import com.project.vo.LoginVo;
import com.project.vo.ResultVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.security.NoSuchAlgorithmException;

@RestController
@RequestMapping("supplier")
public class SupplierController {
    @Autowired
    private ISupplierService supplierService;
    @GetMapping("findById")
    public ResultVo findById(HttpServletRequest req){

        SupplierDto loginUser = SupplierThreadLocal.getSupplier();
        if (loginUser!=null){
            return ResultVo.ok(supplierService.findById(loginUser.getId()));
        }
        return ResultVo.ok();
    }
    @GetMapping("login")
    public ResultVo login(String userName, String password, HttpServletRequest req) throws NoSuchAlgorithmException {
        SupplierDto loginSupplier = supplierService.login(userName, password);
        LoginVo loginVo = new LoginVo();
        if (loginSupplier != null) {//用户存在
            loginVo.setStatus(loginSupplier.getStatus());
            String json= JSON.toJSONString(loginSupplier);
            String token = CreateToken.createToken(json);
            loginVo.setToken(token);


            return ResultVo.ok(loginVo);
        }
        return ResultVo.fail("用户名或密码输入错误");
    }
}
